import {
  getInspectPlanByPage,
  addInspectPlan,
  updateInspectPlan,
  delInspectPlan,
  exportInspectPlan,
  getInspectID,
  getInspectBy,
  receiveInspectSubItem,
  generateInspectTask,
} from '@/services/device/inspectPlan';
import { PlusOutlined } from '@ant-design/icons';
import { tableSearchPublicConfig } from '@/utils/filterUtils';
import { PageHeaderWrapper } from '@ant-design/pro-layout';
import type { ActionType, ProColumns } from '@ant-design/pro-table';
import ProTable from '@ant-design/pro-table';
import moment from 'moment';
import {
  message,
  Modal,
  Tree,
  Button,
  Cascader,
  Checkbox,
  DatePicker,
  Form,
  Col,
  Row,
  Input,
  InputNumber,
  Radio,
  Select,
  Slider,
  Switch,
  TreeSelect,
  Upload,
  Tabs,
  Card,
  Tooltip,
} from 'antd';
import { sortTran, filterTran } from '@/utils/requestUtil';
import React, { useEffect, useRef, useState } from 'react';
import {
  ModalForm,
  ProFormDatePicker,
  ProFormRadio,
  ProFormSelect,
  ProFormText,
} from '@ant-design/pro-components';
import './style.less';
import { getTemplateIdlist } from '@/services/device/inspectStandard';
import { getErrorReportMembers } from '@/services/platform/errorReport';
import InspectTask from '@/pages/device/inspectTask';
import InspectSubItem from '@/pages/device/inspectSubItem';
const InspectPlan: React.FC<{}> = () => {
  const actionRef = useRef<ActionType>();
  const subActionRef = useRef<ActionType>();
  const [modalVisit, setModalVisit] = useState(false); // 新建和编辑提示框
  const [modalVisit1, setModalVisit1] = useState(false); // 巡检详情页面框
  const [modalVisit2, setModalVisit2] = useState(false); // 巡检详情新建和编辑页面框
  const [confirmLoading, setConfirmLoading] = useState(false); //编辑框的disable
  const [formTitle, setFormTitle] = useState('新建'); //F
  const [orderOptions, setOrderOptions] = useState(); //下拉框
  const [createOrUpdate, setCreateOrUpdate] = useState(false); //编辑框的disable
  const [workCodeOptions, setWorkCodeOptions] = useState();
  const [disTimes, setDisTimes] = useState(true);
  const [form] = Form.useForm();
  const detailRef = useRef(null);
  const [inspectTemplateId, setInspectTemplateId] = useState(); //巡检计划详细页关联巡检计划id
  const [templateIdListInfo, setTemplateIdListInfo] = useState([]); //巡检模板Id列表
  const [inspectId, setInspectId] = useState();
  const [clickInspectId, setClickInspectId] = useState('');
  const [inspectMember, setInspectMember] = useState(); //巡检人信息
  const [currentInspectId, setCurrentInspectId] = useState();
  const ref = useRef(null);

  /* 生命周期钩子，用于初始化数据 */
  useEffect(() => {
    getTemplateIdlistInfo();
    getInspectIdInfo();
    getInspectMemberInfo();
  }, []);

  /* 巡检计划有效标记颜色tag组件 */
  const IsValidColorTag = ({ isBlue, text }) => {
    const tagStyle = {
      textAlign: 'center',
      width: '50px',
      height: '27px',
      padding: '5px',
      borderRadius: '3px',
      color: 'white',
      fontSize: '10px',
      backgroundColor: '#13c2c2',
    };
    if (isBlue) {
      tagStyle.backgroundColor = '#13c2c2';
    } else {
      tagStyle.backgroundColor = '#DC6C76';
    }
    return (
      <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
        <div style={tagStyle}>{text}</div>
      </div>
    );
  };

  /* 巡检计划生成功能 */
  const generateInspectTaskFunction = async (inspectId: any) => {
    const params = {
      current: 1,
      pageSize: 20,
      sorters: [],
      filters: [
        {
          andOr: 'and',
          field: 'InspectID',
          operator: 'eq',
          value: inspectId,
        },
      ],
    };
    const result = await generateInspectTask?.(params);
    return result;
  };
  /* 巡检计划任务类型颜色tag组件 */
  const PlanTypeColorTag = ({ text }) => {
    const tagStyle = {
      textAlign: 'center',
      width: '50px',
      height: '27px',
      padding: '5px',
      borderRadius: '3px',
      color: 'white',
      fontSize: '10px',
      backgroundColor: '#13c2c2',
    };
    if (text === '主动') {
      tagStyle.backgroundColor = '#13c2c2';
    } else {
      tagStyle.backgroundColor = '#DC6C76';
    }
    return (
      <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
        <div style={tagStyle}>{text}</div>
      </div>
    );
  };
  const columns: ProColumns[] = [
    {
      title: '序号',
      dataIndex: 'index',
      valueType: 'index',
      align: 'center',
      sorter: true,
      width: 60,
    },
    {
      title: '巡检计划单名称',
      dataIndex: 'inspectDesc',
      align: 'center',
      sorter: true,

      ellipsis: true,
      render: (text) => (
        <Tooltip placement="topLeft" title={text}>
          {text}
        </Tooltip>
      ),
      width: 200,
    },
    {
      title: '巡检计划编号',
      dataIndex: 'inspectID',
      align: 'center',
      sorter: true,

      width: 100,
    },

    {
      title: '巡检人',
      dataIndex: 'inspectBy',
      align: 'center',
      sorter: true,

      width: 80,
      valueType: 'select',
      fieldProps: {
        options: inspectMember,
      },
    },
    {
      title: '巡检周期',
      dataIndex: 'period',
      search: false,

      align: 'center',
      sorter: true,

      width: 80,
    },
    {
      title: '巡检频率',
      dataIndex: 'times',
      search: false,
      width: 100,

      align: 'center',
      sorter: true,

      render: (text: string) => <span> {text} </span>,
    },
    {
      title: '巡检分类',
      align: 'center',
      sorter: true,

      dataIndex: 'planType',
      width: 80,

      valueType: 'select',
      search: false,
      fieldProps: {
        options: [
          {
            label: '巡检',
            value: '巡检',
          },
          {
            label: '保养',
            value: '保养',
          },
        ],
      },
      // fieldProps: {
      //   options: ,
      // },
    },
    {
      title: '任务类别',
      dataIndex: 'category',
      search: false,
      align: 'center',
      sorter: true,

      render: (text: string) => <PlanTypeColorTag text={text} />,
      width: 80,
      //     fieldProps: {
      //   options: ,
      // },
    },
    {
      title: '有效标记',
      dataIndex: 'isValid',
      search: false,
      align: 'center',
      sorter: true,

      render: (text: boolean) => <IsValidColorTag isBlue={text} text={text ? '有效' : '无效'} />,
      width: 80,
    },
    {
      title: '巡检计划模板编号',
      dataIndex: 'templateID',
      search: false,
      align: 'center',
      sorter: true,

      width: 130,
    },
    {
      title: '创建日期', //表头显示的名称
      search: false,

      align: 'center',
      sorter: true,

      dataIndex: 'createTime',
      width: 80,
      hideInTable: true,
    },
    {
      title: '截止日期',
      search: false,

      dataIndex: 'dueTime',
      align: 'center',
      sorter: true,

      width: 80,
    },
    // {
    //   title: '创建人',
    //   dataIndex: 'createBy',
    // },
    // {
    //   title: '创建人', //表头显示的名称
    //   search: false,
    //   dataIndex: 'createName',
    //   width: 100,
    // },

    // {
    //   title: '唯一标识',
    //   dataIndex: 'identification',
    // },
    // {
    //   title: '计划单号',
    //   dataIndex: 'inspectid',
    // },
    // {
    //   title: '计划周期 年/月/周/日',
    //   dataIndex: 'period',
    // },
    // {
    //   title: '更新人',
    //   dataIndex: 'updateBy',
    // },
    {
      title: '操作',
      valueType: 'option',
      key: 'option',
      align: 'center',
      fixed: 'right',
      width: 200,
      render: (text, record, _, action) => [
        <a
          key="editKey"
          onClick={() => {
            setModalVisit(true);
            setCreateOrUpdate(true);
            setFormTitle('编辑');
            console.log('编辑巡检计划信息', record);
            form.setFieldsValue({
              category: record.category,
              createBy: record.createBy,
              dueTime: moment(record.dueTime),
              identification: record.identification,
              inspectBy: record.inspectBy,
              inspectDesc: record.inspectDesc,
              inspectID: record.inspectID,
              isValid: record.isValid ? 'true' : 'false',
              period: record.period,
              planType: record.planType,
              templateID: record.templateID,
              times: String(record.times),
              updateBy: record.updateBy,
              id: record.id,
            });
          }}
        >
          编辑
        </a>,
        <a
          key="detailKey"
          onClick={() => {
            console.log('巡检计划模板id', record.templateid);
            setInspectTemplateId(record.templateID);
            setCurrentInspectId(record.inspectID);
            setModalVisit1(true);
          }}
        >
          查看
        </a>,
        <a
          key="deleteKey"
          onClick={() => {
            Modal.confirm({
              title: '删除',
              content: '确定要删除吗',
              okText: '确认',
              cancelText: '取消',
              onOk: async () => {
                await delInspectPlan({ id: record.id });
                actionRef.current.reload();
              },
            });
          }}
        >
          删除
        </a>,
        <a
          key="createKey"
          onClick={() => {
            const result = generateInspectTaskFunction(record.inspectID);
            result
              .then((data: any) => {
                console.log('DataFetch', data);
                if (data.message === 'success') {
                  message.success('巡检计划任务生成成功！');
                  subActionRef.current?.reload?.();
                } else {
                  message.error('巡检计划任务生成失败！');
                }
              })
              .catch((error: any) => {
                message.error('巡检计划任务生成失败！');
                console.log('Error', error);
              });
          }}
        >
          生成
        </a>,
      ],
    },
  ];
  const handleSubmit = async (values) => {
    setConfirmLoading(true);
    if (formTitle == '新建') {
      console.log('巡检计划新建信息：', values);
      const result = await addInspectPlan(values);
      if (result != null) {
        message.success('添加成功');
        getInspectIdInfo();
        receiveInspectSubItem(values);
      }
    } else {
      console.log(values);
      const result_update = await updateInspectPlan(values);
      if (result_update != null) {
        message.success('编辑成功！');
      }
    }
    setConfirmLoading(false);
    setModalVisit(false);
    actionRef.current.reload();
  };

  //获取工序类型
  const handleChange = async (value: any) => {
    console.log(`selected ${value}`);
    setDisTimes(false);
    if (value == '年') {
      setOrderOptions({
        一月: '一月',
        二月: '二月',
        三月: '三月',
        四月: '四月',
        五月: '五月',
        六月: '六月',
        七月: '七月',
        八月: '八月',
        九月: '九月',
        十月: '十月',
        十一月: '十一月',
        十二月: '十二月',
      });
    } else if (value == '月') {
      setOrderOptions({
        一日: '一日',
        二日: '二日',
        三日: '三日',
        四日: '四日',
        五日: '五日',
        六日: '六日',
        七日: '七日',
        八日: '八日',
        九日: '九日',
        十日: '十日',
        十日: '十日',
        十二日: '十二日',
        十三日: '十三日',
        十四日: '十四日',
        十五日: '十五日',
        十六日: '十六日',
        十七日: '十七日',
        十八日: '十八日',
        十九日: '十九日',
        二十日: '二十日',
        二十日: '二十日',
        二十二日: '二十二日',
        二十三日: '二十三日',
        二十四日: '二十四日',
        二十五日: '二十五日',
        二十六日: '二十六日',
        二十七日: '二十七日',
        二十八日: '二十八日',
        二十九日: '二十九日',
        三十日: '三十日',
        三十一日: '三十一日',
      });
    } else if (value == '周') {
      setOrderOptions({
        周一: '周一',
        周二: '周二',
        周三: '周三',
        周四: '周四',
        周五: '周五',
        周六: '周六',
        周日: '周日',
      });
    } else if (value == '日') {
      setOrderOptions({
        一点: '一点',
        二点: '二点',
        三点: '三点',
        四点: '四点',
        五点: '五点',
        六点: '六点',
        七点: '七点',
        八点: '八点',
        九点: '九点',
        十点: '十点',
        十一点: '十一点',
        十二点: '十二点',
        十三点: '十三点',
        十四点: '十四点',
        十五点: '十五点',
        十六点: '十六点',
        十七点: '十七点',
        十八点: '十八点',
        十九点: '十九点',
        二十点: '二十点',
        二十一点: '二十一点',
        二十二点: '二十二点',
        二十三点: '二十三点',
        二十四点: '二十四点',
      });
    }
  };
  /* 设备巡检计划任务模块 */
  const tabList: tabType[] = [
    {
      name: 'tab1',
      label: '未完成',
      content: (
        <InspectTask
          clickInspectId={clickInspectId}
          taskState={'未完成'}
          subRef={subActionRef}
        ></InspectTask>
      ),
    },
    {
      name: 'tab2',
      label: '已完成',
      content: (
        <InspectTask
          clickInspectId={clickInspectId}
          taskState={'已完成'}
          subRef={subActionRef}
        ></InspectTask>
      ),
    },
  ];
  /* 获取巡检模板编号 */
  const getTemplateIdlistInfo = async () => {
    const param = {
      filters: [],
      sorters: [],
    };
    const result = await getTemplateIdlist(param);
    console.log(result);
    const templateIdList: any[] = [];
    for (const item in result.data) {
      templateIdList.push({ label: result.data[item], value: item });
    }
    setTemplateIdListInfo(templateIdList);
  };
  /* 获取巡检记录编号 */
  const getInspectIdInfo = async () => {
    const param = {
      filters: [],
      sorters: [],
    };
    const result = await getInspectID(param);
    console.log('inspectId:', result);
    setInspectId(result?.data?.InspectId);
  };
  /* 获取巡检人信息 */
  const getInspectMemberInfo = async () => {
    try {
      const errorReportMembersArray = await getErrorReportMembers?.(null);
      setInspectMember(
        errorReportMembersArray.data?.map((item: any) => {
          return { value: item.name, label: item.name };
        }),
      );
      console.log('异常处理人列表：', errorReportMembersArray);
    } catch (e) {
      console.log('获取巡检人接口报错', e);
      message.error('未正常获取巡检人信息');
    }
  };
  return (
    <PageHeaderWrapper title={false} breadcrumb={undefined}>
      <ProTable
        headerTitle="巡检计划查询"
        actionRef={actionRef} //用于触发刷新操作等，看api
        rowKey="id" //表格行 key 的取值，可以是字符串或一个函数
        formRef={ref}
        search={tableSearchPublicConfig}
        size="large"
        onRow={(record) => ({
          onClick: () => {
            setClickInspectId(record.inspectID);
            console.log('巡检计划：', record);
          },
        })}
        toolBarRender={(action, { selectedRows }) => [
          <Button
            key="button"
            icon={<PlusOutlined />}
            onClick={() => {
              getTemplateIdlistInfo();
              setCreateOrUpdate(false);
              setFormTitle('新建');
              form.resetFields();
              setModalVisit(true);
            }}
            type="primary"
          >
            新建
          </Button>,
          <Button
            key="button"
            icon={<PlusOutlined />}
            onClick={() => {
              const filters = filterTran(ref.current.getFieldsValue());
              exportInspectPlan({
                current: 1,
                pageSize: 5000,
                filters: filters,
              }).then((res) => {
                const aLink = document.createElement('a');
                document.body.appendChild(aLink);
                aLink.style.display = 'none';
                aLink.href = window.URL.createObjectURL(res);
                aLink.setAttribute('download', `InspectPlan.xls`);
                aLink.click();
                document.body.removeChild(aLink);
              });
            }}
            type="primary"
          >
            导出
          </Button>,
        ]}
        request={async (params = {}, sort, filter) => {
          const sorters = sortTran(sort);
          const filters = filterTran(params);
          console.log(filters);
          getTemplateIdlistInfo();
          filters.map((item: any) => {
            console.log(item.field[0]);
            const newField = item.field[0].toUpperCase() + item.field.substring(1);
            item.field = newField;
          });
          sorters.map((item: any) => {
            console.log(item.field[0]);
            const newField = item.field[0].toUpperCase() + item.field.substring(1);
            item.field = newField;
          });
          const result = await getInspectPlanByPage({
            ...params,
            sorters: sorters,
            filters: filters,
          });
          console.log(result);
          return {
            data: result.data.content,
            total: result.data.totalElements,
            success: result.success,
          };
        }}
        columns={columns}
        scroll={{ x: 1800, y: 350 }}
        rowSelection={{}}
      />
      {/* 巡检计划任务查询 */}
      {/* <Tabs
        style={{ background: 'white', marginTop: 15 }}
        type="card"
        onChange={(value) => {
          console.log('tab序列信息：', value);
        }}
        destroyInactiveTabPane={true}
        items={tabList.map((item, i) => {
          const id = String(i + 1);
          return {
            label: item.label,
            key: id,
            children: <div>{item.content}</div>,
          };
        })}
      /> */}
      {/* 巡检计划新建表单 */}
      <ModalForm
        visible={modalVisit}
        title={formTitle}
        form={form}
        onFinish={handleSubmit}
        modalProps={{
          destroyOnClose: true,
          onCancel: () => {
            setModalVisit(false);
          },
        }}
        initialValues={{
          inspectID: inspectId,
        }}
      >
        <Row gutter={[50, 0]}>
          <Col span={12}>
            <ProFormText
              name="inspectDesc"
              label="巡检项描述"
              width={330}
              placeholder="请输入巡检项描述"
              rules={[{ required: true, message: '请输入巡检项描述!' }]}
            />
          </Col>
          <Col span={12}>
            <ProFormSelect
              width="md"
              name="inspectBy"
              options={inspectMember}
              label="巡检人"
              placeholder="请输入巡检人"
              rules={[{ required: true, message: '请输入巡检人!' }]}
            />
          </Col>
        </Row>
        <Row gutter={[50, 0]}>
          <Col span={12}>
            <ProFormSelect
              width="md"
              name="period"
              label="巡检周期"
              valueEnum={{
                年: '年',
                月: '月',
                周: '周',
                日: '日',
              }}
              rules={[{ required: true, message: '请选择巡检周期!' }]}
              fieldProps={{
                autoClearSearchValue: true, //选中后清空搜索框
                //使用onChange onBlur
                onChange: (value) => {
                  handleChange(value);
                  return value; //必须要return一个值出去 表单项才会展示值在输入框上
                },
              }}
            />
          </Col>
          <Col span={12}>
            <ProFormSelect
              width="md"
              name="times"
              label="巡检频率"
              tooltip="请先选择巡检周期"
              placeholder="请先选择巡检周期"
              disabled={disTimes}
              valueEnum={orderOptions}
              rules={[{ required: true, message: '请输入巡检频率!' }]}
              fieldProps={{
                mode: 'multiple', //多选
                autoClearSearchValue: true, //选中后清空搜索框
                //使用onChange onBlur
                onChange: (value) => {
                  return value; //必须要return一个值出去 表单项才会展示值在输入框上
                },
              }}
            />
          </Col>
        </Row>
        <Row gutter={[50, 0]}>
          <Col span={12}>
            <ProFormSelect
              width="md"
              name="planType"
              label="巡检分类"
              valueEnum={{
                巡检: '巡检',
                保养: '保养',
              }}
              placeholder="请输入巡检分类"
              rules={[{ required: true, message: '请选择巡检分类!' }]}
            />
          </Col>
          <Col span={12}>
            <ProFormDatePicker
              name="dueTime"
              label="截止日期"
              width={330}
              rules={[{ required: true, message: '请选择截止日期!' }]}
            />
          </Col>
        </Row>
        <Row gutter={[50, 0]}>
          <Col span={12}>
            <ProFormText
              name="inspectID"
              label="巡检计划编号"
              rules={[{ required: true, message: '请输入巡检计划编号!' }]}
              disabled={true}
            />
          </Col>
          <Col span={12}>
            <ProFormSelect
              name="templateID"
              label="巡检计划模板"
              rules={[{ required: true, message: '请选择巡检计划模板!' }]}
              disabled={createOrUpdate}
              options={templateIdListInfo}
            />
          </Col>
        </Row>
        <Row gutter={[50, 0]}>
          <Col span={12}>
            <ProFormRadio.Group
              name="category"
              label="任务类型"
              rules={[{ required: true, message: '请选择任务类型!' }]}
              options={[
                {
                  label: '主动',
                  value: '主动',
                },
                {
                  label: '被动',
                  value: '被动',
                },
              ]}
            />
          </Col>
          <Col span={12}>
            <ProFormRadio.Group
              name="isValid"
              label="有效标记"
              rules={[{ required: true, message: '请选择有效标记!' }]}
              options={[
                {
                  label: '有效',
                  value: 'true',
                },
                {
                  label: '无效',
                  value: 'false',
                },
              ]}
            />
          </Col>
        </Row>
      </ModalForm>
      {/* 巡检详情新建页面 */}
      <ModalForm
        visible={modalVisit2}
        title={'增加'}
        form={form}
        onFinish={handleSubmit}
        modalProps={{
          destroyOnClose: true,
          onCancel: () => {
            setModalVisit2(false);
          },
        }}
      >
        <ProFormText
          name="category"
          label="任务类别"
          rules={[{ required: true, message: '请输入任务类别!' }]}
          disabled={createOrUpdate}
        />
        <ProFormText
          name="inspectBy"
          label="巡检人"
          rules={[{ required: true, message: '请输入巡检人!' }]}
          disabled={createOrUpdate}
        />
        <ProFormText
          name="createBy"
          label="创建人"
          rules={[{ required: true, message: '请输入创建人!' }]}
          disabled={createOrUpdate}
        />
        <ProFormText
          name="inspectDesc"
          label="计划描述"
          rules={[{ required: true, message: '请输入计划描述!' }]}
          disabled={createOrUpdate}
        />
        <ProFormSelect
          width="md"
          name="period"
          label="巡检周期"
          valueEnum={{
            年: '年',
            月: '月',
            周: '周',
            日: '日',
          }}
          rules={[{ required: true, message: '请选择巡检周期!' }]}
          fieldProps={{
            autoClearSearchValue: true, //选中后清空搜索框
            //使用onChange onBlur
            onChange: (value) => {
              handleChange(value);
              return value; //必须要return一个值出去 表单项才会展示值在输入框上
            },
          }}
        />
        <ProFormSelect
          width="md"
          name="times"
          label="巡检频率"
          tooltip="请先选择巡检周期"
          placeholder="请先选择巡检周期"
          valueEnum={orderOptions}
          disabled={disTimes}
          rules={[{ required: true, message: '请选择巡检频率!' }]}
          fieldProps={{
            mode: 'multiple', //多选
            autoClearSearchValue: true, //选中后清空搜索框
            //使用onChange onBlur
            onChange: (value) => {
              return value; //必须要return一个值出去 表单项才会展示值在输入框上
            },
          }}
        />
        <ProFormText
          name="planType"
          label="计划类型 巡检/保养"
          rules={[{ required: true, message: '请输入计划类型!' }]}
          disabled={createOrUpdate}
        />
        <ProFormText
          name="isValid"
          label="是否有效"
          rules={[{ required: true, message: '请输入是否有效!' }]}
          disabled={createOrUpdate}
        />
        <ProFormText
          name="dueTime"
          label="截止日期"
          rules={[{ required: true, message: '请选择截止日期!' }]}
          disabled={createOrUpdate}
        />
      </ModalForm>
      {/* 巡检详情模块 */}
      <Modal
        open={modalVisit1}
        title="巡检计划子项"
        destroyOnClose
        width={1500}
        onCancel={() => {
          setModalVisit1(false);
        }}
        footer={[]}
      >
        {/* 巡检详细模块组件 */}
        <InspectSubItem inspectId={currentInspectId} />
      </Modal>
    </PageHeaderWrapper>
  );
};
export default InspectPlan;
